/**
 * @Description
 * @Author
 * @Date 2021/7/21 08:10
 **/
package model

import (
	"fmt"
	"goskeleton/app/global/variable"
	"goskeleton/app/sqlr/db"
)

type MainModel struct {

}

func NewMainModel() *MainModel {
	return &MainModel{}
}
func (this *MainModel)SendListRun(input db.Parms) (TlistVAR []db.Tlist) {

	listrun:=variable.GormDbSqlserver.Table("MzInvoice.Slave x").Select(`YPID = x.ItemID,
	Num = SUM ( CASE WHEN m.IsReinvoice= 1 THEN - Num ELSE num END ),
	Je = SUM ( CASE WHEN m.IsReinvoice= 1 THEN - Je ELSE je END ),
	JJJe = SUM ( CASE WHEN m.IsReinvoice= 1 THEN - x.yhj* Num ELSE x.yhj* num END )`).
		Joins("join MzInvoice.OpRec m  ON m.SubHospitalID= x.SubHospitalID AND m.Jnh= X.Jnh").
		Where("x.XmlbID=?",-1).
		Where("m.OpTime>=?",input.DTStart).
		Where("m.OpTime<?",input.DTEnd)
	//判断是否有分院编号
	if input.SubHospitalID!="0"{
		listrun.Where("x.SubHospitalID=?",input.SubHospitalID)
	}
	//查询SQL
	listrun.Group("x.ItemID").
		Order("Je desc").
		Find(&TlistVAR)
	return
}
func (this *MainModel)ClearRun(table string)  {
	variable.GormDbSqlserver.Exec("truncate table "+table)
}
func (this *MainModel)CreatedTmp(TlistVAR []db.Tlist)  {
	ct:=make(chan int)
	ci:=len(TlistVAR)%10
	if len(TlistVAR)>0 {
		for ti:=0;ti<ci;ti++{
			go func(ti int) {
				rc:=0
				if ti==ci-1 {
					rc=len(TlistVAR)
				}else{
					rc=100*ti+100
				}
				TlistCli:=TlistVAR[ti*100:rc]
				variable.GormDbSqlserver.Create(&TlistCli)
				ct<-1
			}(ti)
		}
	}
	t:=0;
	for range ct {
		if t==ci-1 {
			close(ct)
		}
		t++
	}
}
func (this *MainModel)Runt() (ConRunVAR []db.Tlist) {
	var SumCountVAR db.SumCount
	variable.GormDbSqlserver.Raw(`select sum(Je) as suum from MzInvoice.Tmplist`).Find(&SumCountVAR)
	ts:=fmt.Sprintf("%f", SumCountVAR.Suum)
	variable.GormDbSqlserver.Table("MzInvoice.Tmplist t").
		Select(`t.YPID,a.ItemName,a.Gg,a.Unit,t.Num,Je=cast(t.Je as money),Rate=cast(t.Je/`+ts+`*100 as money),a.Yhj,a.Price,t.JJJe,
    sGrade=(case when b.Grade=0 then '无等级' when b.grade=1 then '甲级' when b.grade=2 then '乙级' end)`).
		Joins("left outer join Hmis_Data.DrugAndFee.AllHisItemsView a on t.YPID=a.ItemID and a.XmlbID=-1").
		Joins("left outer join Hmis_Data.DrugMaterial.DMItem b on t.YPID=b.YPID").
		Order("t.Je desc").
		Find(&ConRunVAR)
	return
}